/*
 * Copyright (c) 2022 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import { isPluralElement, isLiteralElement, isSelectElement } from './types.js';
import { pegParse } from './parser.js';
const PLURAL_HASHTAG_REGEX = /(^|[^\\])#/g;
/**
 * Whether to convert `#` in plural rule options
 * to `{var, number}`
 * @param el AST Element
 * @param pluralStack current plural stack
 */
export function normalizeHashtagInPlural(els) {
    els.forEach(el => {
        // If we're encountering a plural el
        if (!isPluralElement(el) && !isSelectElement(el)) {
            return;
        }
        // Go down the options and search for # in any literal element
        Object.keys(el.options).forEach(id => {
            const opt = el.options[id];
            // If we got a match, we have to split this
            // and inject a NumberElement in the middle
            let matchingLiteralElIndex = -1;
            let literalEl = undefined;
            for (let i = 0; i < opt.value.length; i++) {
                const el = opt.value[i];
                if (isLiteralElement(el) && PLURAL_HASHTAG_REGEX.test(el.value)) {
                    matchingLiteralElIndex = i;
                    literalEl = el;
                    break;
                }
            }
            if (literalEl) {
                const newValue = literalEl.value.replace(PLURAL_HASHTAG_REGEX, `$1{${el.value}, number}`);
                const newEls = pegParse(newValue);
                opt.value.splice(matchingLiteralElIndex, 1, ...newEls);
            }
            normalizeHashtagInPlural(opt.value);
        });
    });
}
